/**
 * @Description:
 * @Author: ds
 * @Date: 2020-10-10 9:18
 */
package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.common.FileKit;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExcelKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.query.*;
import org.jsola.hr.service.ICompanyService;
import org.jsola.hr.service.IHrPermissionService;
import org.jsola.hr.service.IStatisticsPageService;
import org.jsola.hr.vo.*;
import org.jsola.hr.vo.excel.ChildCompanyExportVO;
import org.jsola.hr.vo.excel.CompanyWithEmpCountExportVO;
import org.jsola.hr.vo.excel.GroupCompanyExportVO;
import org.jsola.hr.vo.permission.RoleMemberVO;
import org.jsola.log.vo.ServiceLogListVO;
import org.jsola.permission.exception.PermissionException;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.jsola.hr.constant.HrPermissionConstants.*;

@RestController("statisticsPageController")
@RequestMapping(HrConstants.API_PATH + "/v1/statisticsPage")
public class StatisticsPageController implements IStatisticsPageControllerAPI {

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IHrPermissionService hrPermissionService;

    @Autowired
    private IStatisticsPageService statisticsPageService;

    @Override
    @PostMapping(value = "/empTodayAddExport")
    public ResponseEntity<Resource> todayAddExport(@Valid @RequestBody StatisicsPageEmpExportQuery statisicsPageEmpExportQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // 模板文件
        InputStream is = statisticsPageService.todayAddExport(statisicsPageEmpExportQuery, tokenUser);
        ParamException.notNull(is, "模板生成失败");

        // 编码文件名，防止乱码
        String filenames = new String("今日新增员工".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new InputStreamResource(is));
    }

    @Override
    @PostMapping(value = "/selectStatisticsCount")
    public Result<StatisticsPageVO> selectStatisticsCount(@RequestBody CompanyIdSQuery companyIds) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                statisticsPageService.selectStatisticsCount(companyIds.getCompanyIds(), companyIds.getType(), tokenUser)
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<ChildCompanyExportVO>> listAll(@Valid ChildCompanyQuery childCompanyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看子公司信息权限校验
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_ENTERPRISEOVERVIEW_SUBCOMPANY), PERMISSION_DENIED_MESSAGE);
        List<ChildCompanyExportVO> exportVOList = statisticsPageService.getAllChildComanyWithAdminForExport(
                childCompanyQuery.getName(), tokenUser, childCompanyQuery.getIds());
        return Result.success(
                exportVOList
                //statisticsPageService.select(childCompanyQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping("/exportComanyWithEmpCount")
    public ResponseEntity<Resource> exportComanyWithEmpCount(@Valid CompanyQuery companyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导出权限校验

        // 要导出的数据
        List<CompanyListVO> companyListVOList = statisticsPageService.selectAll(tokenUser, companyQuery);
        // 导出excel
        String excelFilePath = ExcelKit.exportExcel("childCompany", "用工单位信息", CompanyWithEmpCountExportVO.class, companyListVOList);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @PostMapping(value = "/selectComanyWithEmpCount")
    public Result<Page<CompanyListVO>> listAll(@Valid @RequestBody CompanyQuery companyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司权限校验

        return Result.success(
                statisticsPageService.selectCompanyAndEmpCount(tokenUser, companyQuery)
        );
    }


    @Override
    @GetMapping(value = "/selectChildComanyWithAdmin")
    public Result<Page<CompanyListVO>> listAllChildComanyWithAdmin(@Valid CompanyQuery companyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司权限校验

        return Result.success(
                statisticsPageService.selectCompanyAndEmpCount(tokenUser, companyQuery)
        );
    }

    @Override
    @PostMapping(value = "/selectAllStaff")
    public Result<Page<StatisticsEmpInfoVO>> selectAllStaff(@RequestBody EmpBySiteQuery empBySiteQuery) {
        TokenUser tokenUser = UserContext.getUser();
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_ENTERPRISEOVERVIEW_EMP), PERMISSION_DENIED_MESSAGE);
        return Result.success(
                statisticsPageService.selectAllStaff(empBySiteQuery, tokenUser)
        );
    }

    @Override
    @GetMapping("/export")
    public ResponseEntity<Resource> export(@Valid ChildCompanyQuery childCompanyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导出权限校验

        // 要导出的数据
        List<ChildCompanyExportVO> exportVOList = statisticsPageService.getAllChildComanyWithAdminForExport(
                childCompanyQuery.getName(), tokenUser, childCompanyQuery.getIds());
        // 导出excel
        String excelFilePath = ExcelKit.exportExcel("listAllChildComanyWithAdmin", "子公司列表",
                ChildCompanyExportVO.class, exportVOList);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8),
                StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }


    @Override
    @GetMapping(value = "/empContractInfoList")
    public Result<Page<EmpContractInfoVO>> empContractInfoList(@Valid EmpInfoQuery empInfoQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司权限校验

        return Result.success(
                statisticsPageService.empContractInfoList(empInfoQuery, tokenUser)
        );
    }


    @Override
    @GetMapping(value = "/getSubCompany")
    public Result<List<CompanyVO>> getSubCompany(@Valid ChildCompanyQuery childCompanyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司权限校验

        return Result.success(
                statisticsPageService.getSubCompany(childCompanyQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/getChildCompanyAdmin")
    public Result<List<RoleMemberVO>> getChildCompanyAdmin(@Valid ChildCompanyQuery childCompanyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司权限校验

        return Result.success(
                statisticsPageService.getChildCompanyAdmin(childCompanyQuery, tokenUser)
        );
    }


    @Override
    @PostMapping(value = "/getStatisticsEmpInfoContractCount")
    public Result<List<StatisticsEmpInfoContractCountVO>> getStatisticsEmpInfoContractCount(@RequestBody StatisticsContractQuery statisticsContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司权限校验

        return Result.success(
                statisticsPageService.getStatisticsEmpInfoContractCount(statisticsContractQuery, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/empEduCount")
    public Result<EmpEduCountVO> empEduCount(@RequestBody CompanyIdSQuery companyIds) {
        TokenUser tokenUser = UserContext.getUser();
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_ENTERPRISEOVERVIEW_EMP), PERMISSION_DENIED_MESSAGE);

        return Result.success(
                statisticsPageService.empEduCount(companyIds.getCompanyIds(), tokenUser)
        );
    }


    @Override
    @PostMapping(value = "/selectAllStaffExport")
    public ResponseEntity<Resource> selectAllStaffExport(@Valid @RequestBody StatisicsPageEmpExportQuery statisicsPageEmpExportQuery) {
        TokenUser tokenUser = UserContext.getUser();
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_ENTERPRISEOVERVIEW_EMP), PERMISSION_DENIED_MESSAGE);
        String excelFilePath = statisticsPageService.selectAllStaffExport(statisicsPageEmpExportQuery, tokenUser);
        String filenames = FileKit.getNameAndEncode(excelFilePath);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @PostMapping(value = "/selectCompanyAndEmpCountStatistics")
    public Result<StatisticsPageVO> selectCompanyAndEmpCountStatistics(@RequestBody CompanyIdSQuery companyIds) {
        TokenUser tokenUser = UserContext.getUser();
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_WORKBENCH_WORKSTATION), PERMISSION_DENIED_MESSAGE);

        return Result.success(
                statisticsPageService.selectCompanyAndEmpCountStatistics(companyIds.getCompanyIds(), companyIds.getType(), tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/selectSocCount")
    public Result<StatisticsPageVO> selectSocCount(@RequestBody CompanyIdSQuery companyIdSQuery) {
        TokenUser tokenUser = UserContext.getUser();
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_WORKBENCH_WORKSTATION), PERMISSION_DENIED_MESSAGE);

        return Result.success(
                statisticsPageService.selectSocCount(companyIdSQuery.getYear(), companyIdSQuery.getMonth(),
                        companyIdSQuery.getCompanyIds(), tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/selectServiceLog")
    public Result<Page<ServiceLogListVO>> selectServiceLog(@RequestBody @Valid ServiceLogFillQuery serviceLogQuery) {
        TokenUser tokenUser = UserContext.getUser();
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_WORKBENCH_WORKSTATION), PERMISSION_DENIED_MESSAGE);

        return Result.success(
                statisticsPageService.selectServiceLog(serviceLogQuery, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/selectHomeEmpCount")
    public Result<StatisticsPageVO> selectHomeEmpCount(@RequestBody CompanyIdSQuery companyIdSQuery) {
        TokenUser tokenUser = UserContext.getUser();
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_WORKBENCH_WORKSTATION), PERMISSION_DENIED_MESSAGE);

        return Result.success(
                statisticsPageService.selectHomeEmpCount(tokenUser, companyIdSQuery.getYear(),
                        companyIdSQuery.getMonth(), companyIdSQuery.getCompanyIds())
        );
    }

    @Override
    @PostMapping(value = "/updateSitePic")
    public Result<Integer> updateSitePic(@Valid String picUrl) {
        TokenUser tokenUser = UserContext.getUser();
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_WORKBENCH_WORKSTATION), PERMISSION_DENIED_MESSAGE);

        return Result.success(
                statisticsPageService.updateSitePic(picUrl, tokenUser)
        );
    }

    @Override
    @GetMapping("/pageChildCompany")
    public Result<Page<ChildCompanyVO>> pageChildCompany(ChildCompanyQuery childCompanyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司权限校验
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_ENTERPRISEOVERVIEW_EMP), PERMISSION_DENIED_MESSAGE);

        return Result.success(
                statisticsPageService.pageChildCompany(childCompanyQuery, tokenUser)
        );
    }

    @Override
    @PostMapping("/exportChildCompany")
    public ResponseEntity<Resource> exportChildCompany(@RequestBody @Valid ChildCompanyQuery childCompanyQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看公司权限校验
        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(), HR_ENTERPRISEOVERVIEW_EMP), PERMISSION_DENIED_MESSAGE);
        List<GroupCompanyExportVO> list = statisticsPageService.exportChildCompany(childCompanyQuery, tokenUser);
        // 导出excel
        String excelFilePath = ExcelKit.exportExcel("groupChildCompany", "用工单位分组",
                ChildCompanyVO.class, list);
        // 编码文件名，防止乱码
        String filenames = FileKit.getNameAndEncode(excelFilePath);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }
}
